package xyc.szk.utils;
/*
 * @Description: 获取数据库连接对象
 * @Author: 山志凯
 * @Date: 2021-06-02
 * @Time: 08:31
 */

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static DataSource ds=null;
    static {
        //Class.forName("com.mysql.jdbc.Driver");//不要硬编码，用配置文件的方式来
        //读配置文件，通过类加载器
        Properties p = new Properties();
        try {
            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            p.load(in);
            //加载mysql的驱动
            //Class.forName(p.getProperty("jdbc.properties"));
            //构造一个dbcp数据源对象给成员ds
            BasicDataSource bd = BasicDataSourceFactory.createDataSource(p);
//            BasicDataSource bd = new BasicDataSource();
//            bd.setDriverClassName(p.getProperty("jdbc,properties"));
//            bd.setUrl(p.getProperty("jdbc.url"));
//            bd.setUsername("jdbc.user");
//            bd.setPassword("jdbc.password");
              ds=bd;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    public static DataSource getDataSource() {
        return ds;
    }
}
